package com.aischool.service;

import java.util.List;

import com.aischool.utils.RegexUtil;
import com.aischool.utils.StringUtil;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class AiAppArticleCatService {

	public List<Record> getAll(int app_id, int org_id, int type_id){
		return Db.find("SELECT * FROM ai_app_article_cat WHERE app_id = ? AND org_id = ? AND type_id = ?", app_id, org_id, type_id);
	}
	
	public boolean updateAppArticleCat(int app_id, int org_id, int type_id, String ids) {
		boolean bf = false;
		bf = Db.tx(() -> {
			int ir = Db.delete("DELETE FROM ai_app_article_cat WHERE app_id = ? AND org_id = ? AND type_id = ?", app_id, org_id, type_id);
			if (StrKit.notBlank(ids) && RegexUtil.isSqlIds(ids)) {
				ir = Db.update("INSERT INTO ai_app_article_cat(app_id, org_id, type_id, cat_id) " + 
						"SELECT ?, ?, ?, CAST(tt.ids AS INTEGER) " + 
						"FROM (SELECT regexp_split_to_table(COALESCE(?,''),E',') AS ids) AS tt",
						app_id, org_id, type_id, StringUtil.trim(ids, ','));
			}
			return ir>0;
		});
		return bf;
	}
	
	public boolean setDefaultAppArticleCat(int app_id, int org_id) {

		Db.delete("DELETE FROM ai_app_article_cat WHERE app_id = ? AND org_id = ?", app_id, org_id);
		int ir = Db.update("INSERT INTO ai_app_article_cat(app_id, org_id, type_id, cat_id) " + 
				"SELECT ?, ?, b.type_id, b.cat_id FROM ai_article_cat b \r\n" + 
				"WHERE b.link_course = 1 AND b.cat_state = 1",
				app_id, org_id);
		return ir>0;
	}
}
